<?php namespace App\Http\Middleware;

use App\Models\Visitlog;
use App\Repository\VisitlogRepository;
use Closure;
use App\Models\Users;
use App\Models\Employee;
use Illuminate\Support\Facades\DB;

class AuthkeyMiddleware {

	public function __construct()
	{
	}
	/**
	 * Handle an incoming request.
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request,Closure $next)
	{
		$hour = date('H', time());
		if($hour>='01' && $hour <= '06' && $request->getClientIp() != $_SERVER['SERVER_ADDR'] && $request->getClientIp() != '127.0.0.1' ){
			$tables = array_map('reset', \DB::select('SHOW TABLES'));
			$ishave = in_array('flow_visit_log',$tables);
			if($ishave){
				$visitlogmodel = new Visitlog();
				$visitlog = new VisitlogRepository($visitlogmodel);
				$data = array();
				$data['url'] = $request->path();
				$data['IP'] = $request->getClientIp();
				$data['type'] = $request->method();
				if(isset($request['userId'])){
					$data['filed1'] = $request['userId'];
					$user =Users::select(['id','username'])->find($request['userId']);
					if($user && isset($user->username)){
						$data['filed1'] = $user->id;
						$data['filed2'] = $user->username;
					}
				}
				$visitlog->store($data);
			}
		}
		$list['code']="-1";$list['msg']="参数错误代理不存在";$list['data']=array();
		$userId=$request['userId'];$times=$request['times'];
		if(strlen($times) == 13 )$times =strtotime(date('Y-m-d H:i:s',$times/1000));
		if( time()-$times>10*60)
		{
			$list['msg']="参数错误,请检查时间戳";
			return response($list);
		}	
		if( $userId )//&& empty($apikey) 
		{
			$request->user = Users::find($userId);
			if( $request->user )
			{
				$times=$request['times'];
				$apikey=$request->user->apikey;$sign=$request['sign'];
				$jmstr = strtoupper(md5("userId=".$userId."&apikey=".$apikey."&times=".$times));
				if( $sign!=$jmstr ){
					$request->user=array();//用户名加apikey验证失败
					$list['code']="-2";$list['msg']="签名错误";
				}
				else if( !empty($request->user->bindip) && !strstr($request->user->bindip,$request->getClientIp()) ){
					$request->user=array();//有IP验证的对IP进行验证
					$list['code']="-3";$list['msg']="IP验证失败";
				}
				else if( $request->user->layer!=2 )
				{
					$request->user=array();//有IP验证的对IP进行验证
				}
			}
		}

		$request['user'] = $request->user;

        $request['page_size']   =   $request->has('length') && $request->get('length') > 0 ? $request->get('length') : 10;
        $request['start']       =   $request->has('start') && $request->get('start') > 0 ? $request->get('start') : 0;
        $request['orderby']     =   'id';
        $request['orderdir']    =   'desc';
        $request['searchvalue'] =   isset($request['search']['value']) && $request['search']['value'] != '' ? $request['search']['value'] : '';

        if(isset($request['order'][0]['dir']) && $request['order'][0]['dir'] != '')
        {
            $request['orderby']     =   $request['columns'][$request['order'][0]['column']]['data'];
            $request['orderdir']    =   $request['order'][0]['dir'];
        }

        return ( $request->user ) ? $next($request): response($list);
	}
}
